# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class Repair(models.Model):
    """设备报修模型"""
    _name = 'device.repair'
    _description = '设备报修管理'
    _order = 'repair_date desc, id desc'
    _rec_name = 'display_name'
    _inherit = ['device.permission.mixin']
    
    # 关联设备
    equipment_id = fields.Many2one('device.equipment', '设备', required=True, ondelete='cascade')
    equipment_name = fields.Char('设备名称', related='equipment_id.name', store=True)
    equipment_code = fields.Char('设备编号', related='equipment_id.code', store=True)
    equipment_category = fields.Char('设备类别', related='equipment_id.category_name', store=True)
    equipment_model = fields.Char('设备型号', related='equipment_id.model', store=True)
    
    # 报修基础信息
    repair_date = fields.Datetime('报修日期', required=True, default=fields.Datetime.now)
    repair_content = fields.Text('报修内容', required=True)
    
    # 报修人员
    reporter_id = fields.Many2one('device.user', '报修人', required=True)
    reporter_name = fields.Char('报修人姓名', related='reporter_id.nick_name', store=True)
    contact_phone = fields.Char('联系电话')
    
    # 故障类型
    fault_type = fields.Selection([
        ('mechanical', '机械故障'),
        ('electrical', '电气故障'),
        ('software', '软件故障'),
        ('hydraulic', '液压故障'),
        ('pneumatic', '气动故障'),
        ('other', '其他故障')
    ], string='故障类型', required=True)
    
    # 紧急程度
    urgency = fields.Selection([
        ('low', '低'),
        ('medium', '中'),
        ('high', '高'),
        ('critical', '紧急')
    ], string='紧急程度', default='medium', required=True)
    
    # 报修状态
    status = fields.Selection([
        ('submitted', '已提交'),
        ('confirmed', '已确认'),
        ('assigned', '已分派'),
        ('repairing', '维修中'),
        ('testing', '测试中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
        ('rejected', '已拒绝')
    ], string='报修状态', default='submitted', required=True)
    
    # 处理信息
    assigned_to = fields.Many2one('device.user', '分派给')
    assigned_date = fields.Datetime('分派时间')
    repair_start_date = fields.Datetime('开始维修时间')
    repair_end_date = fields.Datetime('完成维修时间')
    
    # 故障分析
    fault_analysis = fields.Text('故障分析')
    repair_solution = fields.Text('维修方案')
    repair_process = fields.Text('维修过程')
    repair_result = fields.Text('维修结果')
    
    # 费用信息
    estimated_cost = fields.Float('预估费用', digits=(16, 2))
    actual_cost = fields.Float('实际费用', digits=(16, 2))
    parts_cost = fields.Float('配件费用', digits=(16, 2))
    labor_cost = fields.Float('人工费用', digits=(16, 2))
    
    # 停机时间
    downtime_hours = fields.Float('停机时长（小时）', compute='_compute_downtime_hours', store=True)
    
    # 文件附件
    attachment_ids = fields.One2many('ir.attachment', 'res_id', 
                                   domain=[('res_model', '=', 'device.repair')], 
                                   string='报修附件')
    
    # 附件URL字段 - 存储通过公共上传接口上传的文件URL
    attachment_urls = fields.Text('附件URL列表', help='存储文件URL，多个URL用换行分隔')
    fault_image_urls = fields.Text('故障图片URL', help='故障现场图片的URL，多个URL用换行分隔')
    repair_report_url = fields.Char('维修报告URL', help='维修报告文件的URL')
    before_repair_urls = fields.Text('维修前图片URL', help='维修前图片的URL，多个URL用换行分隔')
    after_repair_urls = fields.Text('维修后图片URL', help='维修后图片的URL，多个URL用换行分隔')
    invoice_url = fields.Char('费用发票URL', help='维修费用发票的URL')
    
    # 显示名称
    display_name = fields.Char('显示名称', compute='_compute_display_name', store=True)
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Char('创建者')
    update_by = fields.Char('更新者')
    remark = fields.Text('备注')
    
    @api.depends('repair_start_date', 'repair_end_date')
    def _compute_downtime_hours(self):
        for record in self:
            if record.repair_start_date and record.repair_end_date:
                delta = record.repair_end_date - record.repair_start_date
                record.downtime_hours = delta.total_seconds() / 3600.0
            else:
                record.downtime_hours = 0.0
    
    @api.depends('equipment_id', 'repair_date', 'fault_type')
    def _compute_display_name(self):
        for record in self:
            if record.equipment_id and record.repair_date:
                fault_type_dict = dict(record._fields['fault_type'].selection)
                fault_type_name = fault_type_dict.get(record.fault_type, record.fault_type)
                record.display_name = f"{record.equipment_id.name} - {fault_type_name} ({record.repair_date.strftime('%Y-%m-%d %H:%M')})"
            else:
                record.display_name = "新报修记录"
    
    @api.constrains('estimated_cost', 'actual_cost', 'parts_cost', 'labor_cost')
    def _check_costs(self):
        for record in self:
            if record.estimated_cost < 0 or record.actual_cost < 0 or record.parts_cost < 0 or record.labor_cost < 0:
                raise ValidationError('费用不能为负数。')
    
    @api.constrains('repair_start_date', 'repair_end_date')
    def _check_repair_dates(self):
        for record in self:
            if record.repair_start_date and record.repair_end_date:
                if record.repair_end_date < record.repair_start_date:
                    raise ValidationError('完成维修时间不能早于开始维修时间。')
    
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['create_time'] = fields.Datetime.now()
            if self.env.user:
                vals['create_by'] = self.env.user.name
        return super().create(vals_list)
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        if self.env.user:
            vals['update_by'] = self.env.user.name
        return super().write(vals)
    
    def action_confirm_repair(self):
        """确认报修"""
        self.write({'status': 'confirmed'})
    
    def action_assign_repair(self):
        """分派维修"""
        self.write({
            'status': 'assigned',
            'assigned_date': fields.Datetime.now()
        })
    
    def action_start_repair(self):
        """开始维修"""
        self.write({
            'status': 'repairing',
            'repair_start_date': fields.Datetime.now()
        })
    
    def action_complete_repair(self):
        """完成维修"""
        self.write({
            'status': 'completed',
            'repair_end_date': fields.Datetime.now()
        })
    
    def action_cancel_repair(self):
        """取消报修"""
        self.write({'status': 'cancelled'})
    
    def action_reject_repair(self):
        """拒绝报修"""
        self.write({'status': 'rejected'})
